#include "MenuState.h"

MenuState* MenuState::menuState = NULL;

MenuState::MenuState(sf::RenderWindow* window, sfge::StateManager* mgr) : State(window, mgr)
{

}

void MenuState::init()
{
    loop.OpenFromFile("Data/Audio/loop.ogg");
    loop.SetLoop(true);
    loop.Play();
    if(!playMusic)
        loop.SetVolume(0);
    font.LoadFromFile("Data/Fonts/Battlev2.TTF");
    background.SetTexture(rm->getTexture("menu.png"));
    cursorSprite.SetTexture(rm->getTexture("cursor.png"));
    playButton = new Button("Play", 50, 200);
    optionsButton = new Button("Options", 50, 280);
    statsButton = new Button("Stats", 50, 360);
    quitButton = new Button("Quit", 50, 440);
}

void MenuState::cleanup()
{
    /*delete playButton;
    delete optionsButton;
    delete statsButton;
    delete quitButton;*/
}

void MenuState::resume()
{
    if(playMusic)
    {
        loop.SetVolume(100);
    }
    else
    {
        loop.SetVolume(0);
    }

}

void MenuState::handle()
{
    sf::Event Event;
    while (window->PollEvent(Event))
    {
        switch (Event.Type)
        {
            case sf::Event::Closed:
                window->Close();
                break;
            case sf::Event::MouseMoved:
                    checkButtons(window->ConvertCoords(sf::Mouse::GetPosition(*window).x, 0).x, window->ConvertCoords(0, sf::Mouse::GetPosition(*window).y).y);
                break;
            case sf::Event::MouseButtonPressed:
                if(Event.MouseButton.Button == sf::Mouse::Left)
                    clicked(window->ConvertCoords(sf::Mouse::GetPosition(*window).x, 0).x, window->ConvertCoords(0, sf::Mouse::GetPosition(*window).y).y);
                break;
            default: break;
        }
    }
}

void MenuState::checkButtons(float x, float y)
{
    playButton->checkHL(x, y);
    optionsButton->checkHL(x, y);
    statsButton->checkHL(x, y);
    quitButton->checkHL(x, y);
}

void MenuState::clicked(float x, float y)
{
    if(playButton->isClicked(x, y))
    {
        loop.SetVolume(0);
        stateManager->pushState(GameState::Instance(window, stateManager));
    }
    if(optionsButton->isClicked(x, y))
        stateManager->pushState(OptionsState::Instance(window, stateManager));
    if(statsButton->isClicked(x,y))
        stateManager->pushState(StatsState::Instance(window, stateManager));
    if(quitButton->isClicked(x, y))
        stateManager->popState();
}

void MenuState::draw()
{
    cursorSprite.SetPosition(window->ConvertCoords(sf::Mouse::GetPosition(*window).x, 0).x, window->ConvertCoords(0, sf::Mouse::GetPosition(*window).y).y);
    window->Clear(sf::Color(200, 255, 0));
    window->Draw(background);
    playButton->draw(window);
    optionsButton->draw(window);
    statsButton->draw(window);
    quitButton->draw(window);
    window->Draw(cursorSprite);
    window->Display();
}
